package midi;

import java.util.LinkedList;


import javax.sound.midi.MidiEvent;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;

import midi.IntervalOperations.interval;

public class MidiChord implements Trackable{
	
	private LinkedList<MidiSound> sounds;
	private long length;
	
	public MidiChord(LinkedList<MidiSound> sounds, long length){
		this.sounds = sounds;
		this.length = length;
	}
	
	public LinkedList<MidiSound> getMidiSounds(){
		return this.sounds;
	}
	
	public void setMidiSounds(LinkedList<MidiSound> sounds){
		this.sounds = sounds;
	}
	
	public long getLength(){
		return this.length;
	}
	
	public void setLength(long length){
		this.length = length;
	}
	
	public MidiSound getRootMidiSound(){
		return sounds.element();
	}
	
	public void setRootMidiSound(MidiSound rootMidiSound){
		if (!(sounds.element().equals(rootMidiSound))){
			sounds.remove(rootMidiSound);
			sounds.addFirst(rootMidiSound);
		}
	}
	
	public void addSound(MidiSound sound){
		this.sounds.add(sound);
	}
	
	public void removeSound(MidiSound sound){
		this.sounds.remove(sound);
	}
	
	public void addSound(interval interval, int velocity){
		addSound(new MidiSound(getRootMidiSound().getPitch().raise(interval), velocity));
	}

	@Override
	public void addToTrack(Track track, int channel, long prevTicks) {
		try{
			for (MidiSound sound : sounds)
			{			
				ShortMessage msg = new ShortMessage();
				msg.setMessage(ShortMessage.NOTE_ON, channel, sound.getNoteNumber(), sound.getVelocity());

				track.add(new MidiEvent(msg, prevTicks));

				ShortMessage endMsg = new ShortMessage();
				endMsg.setMessage(ShortMessage.NOTE_OFF, channel, sound.getNoteNumber(), 0);
			
				track.add(new MidiEvent(endMsg, prevTicks + length));
			}
		}
		catch (Exception e){
		}			
	}
	
	
}
